package com.echoplots.jdbctemplate.dao.impl;

import java.sql.Types;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import com.echoplots.jdbctemplate.dao.UserDao;
import com.echoplots.jdbctemplate.entity.User;
import com.echoplots.jdbctemplate.mapper.UserMapper;
@Repository("userDao")
public class UserDaoImpl implements UserDao{
	@Autowired
	private JdbcTemplate jdbcTemplate;
	@Override
	public int add(User user) {
		String sql = "insert into user(name,age) values(:name,:age)";
		NamedParameterJdbcTemplate npjt = new NamedParameterJdbcTemplate(this.jdbcTemplate.getDataSource());
		return npjt.update(sql, new BeanPropertySqlParameterSource(user));
	}

	@Override
	public int update(User user) {
		String sql = "update user set name = ?,age = ? where name = ?";
		Object[] args = { user.getName(), user.getAge(), user.getName() };
		int[] argTypes = { Types.VARCHAR, Types.INTEGER, Types.VARCHAR };
		return this.jdbcTemplate.update(sql, args, argTypes);
	}

	@Override
	public int deleteById(Integer id) {
		String sql = "delete from user where id = ?";
		Object[] args = { id };
		int[] argTypes = { Types.INTEGER };
		return this.jdbcTemplate.update(sql, args, argTypes);
	}

	@Override
	public List<Map<String, Object>> queryUsersListMap() {
		String sql = "select * from user";
		return this.jdbcTemplate.queryForList(sql);
	}

	@Override
	public User queryUserByName(String name) {
		String sql = "select * from user where name = ?";
		Object[] args = { name };
		int[] argTypes = { Types.VARCHAR };
		List<User> userList = this.jdbcTemplate.query(sql, args, argTypes, new UserMapper());
		if (userList != null && userList.size() > 0) {
			return userList.get(0);
		} else {
			return null;
		}
	}

}
